package com.ruoyi.combat.util.weibo;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class WeiboUtil {
    @Value("${weibo.url}")
    private String url;

    /**
     * {
     *     "code": 200,
     *     "msg": "获取登录状态成功",
     *     "data": {
     *         "uid": "6972663192",
     *         "status": "login_success",
     *         "qrcode_url": "",
     *         "message": "登录成功",
     *         "logged_in": true
     *     }
     * }
     * 获取二维码
     * @param uid
     * @return
     */
    public String getQrcodelogin(String uid) {
        String urlPath = url + "/api/weibo/qrcodelogin";
        Map<String, String> data = new HashMap<>();
        data.put("uid", uid);
        String jsonStr = JSONUtil.toJsonStr(data);

        boolean isSuccess = true;
        String qrcode_url = "";
        while (isSuccess) {
            String post = HttpUtil.post(urlPath, jsonStr);
            log.info("获取二维码结果：{}", post);
            if (StringUtils.isNotEmpty(post)) {
                Map<String, Object> map = JSONUtil.parseObj(post);
                if (map.get("code").equals(200)) {
                    Map<String, Object> dataMap = (Map<String, Object>) map.get("data");
                    qrcode_url = (String) dataMap.get("qrcode_url");
                    if (StringUtils.isNotEmpty(qrcode_url)) {
                        break;
                    }
                }
            } else {
                log.error("获取二维码失败");
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return qrcode_url;
    }

    /**
     * 切换微博用户
     * @param uid
     * @return
     */
    public boolean isLogin(String uid) {
        String urlPath = url + "/api/weibo/login";
        Map<String, String> data = new HashMap<>();
        data.put("uid", uid);
        String jsonStr = JSONUtil.toJsonStr(data);
        String post = HttpUtil.post(urlPath, jsonStr);
        if (StringUtils.isNotEmpty(post)) {
            Map<String, Object> map = JSONUtil.parseObj(post);
            Object code = map.get("code");
            if (code != null && "200".equals(String.valueOf(code))) {
                log.error("切换微博用户成功");
                return true;
            }
            log.error("切换微博用户失败");
            return false;
        } else {
            log.error("切换微博用户失败");
            return false;
        }
    }

    /**
     * 获取关注列表
     * @param uid
     * @return
     */
    public String get_follows(String uid) {
        String urlPath = url + "/api/weibo/get_follows";
        isLogin(uid);
        Map<String, Object> data = new HashMap<>();
        data.put("uid", uid);
        List<String> list = new ArrayList<>();
        list.add(uid);
        data.put("target_ids", list);
        String jsonStr = JSONUtil.toJsonStr(data);
        String post = HttpUtil.post(urlPath, jsonStr);
        return post;
    }

    public String getUsersInfo(String uid,List<String> list) {
        String urlPath = url + "/api/weibo/getusersinfo";
        Map<String, Object> data = new HashMap<>();
        data.put("uid", uid);
        list.add(uid);
        data.put("target_ids", list);
        String jsonStr = JSONUtil.toJsonStr(data);
        String post = HttpUtil.post(urlPath, jsonStr);
        return post;
    }


    public void follow(String uid, List<String> target_ids) {
        isLogin(uid);
        String urlPath = url + "/api/weibo/follow";
        log.info("用户：{}关注：{}", uid, target_ids);
        Map<String, Object> data = new HashMap<>();
        data.put("uid", uid);
        data.put("target_ids", target_ids);
        String jsonStr = JSONUtil.toJsonStr(data);
        String post = HttpUtil.post(urlPath, jsonStr);
        log.info("关注结果: " + post);
    }

    public void unfollow(String uid, List<String> target_ids) {
        isLogin(uid);
        String urlPath = url + "/api/weibo/unfollow";
        log.info("用户：{}取消关注：{}", uid, target_ids);
        Map<String, Object> data = new HashMap<>();
        data.put("uid", uid);
        data.put("target_ids", target_ids);
        String jsonStr = JSONUtil.toJsonStr(data);
        String post = HttpUtil.post(urlPath, jsonStr);
        log.info("取消关注结果: " + post);
    }

    public String send_weibo(String uid, String content, List<Map> fileList) {
        String urlPath = url + "/api/weibo/send_weibo";
        isLogin(uid);
        // 使用RestTemplate上传文件
        RestTemplate restTemplate = new RestTemplate();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);
        // 准备MultiValueMap来保存文件和其他表单字段
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        if (fileList != null) {
            for (int i = 0; i < fileList.size(); i++) {
                Map map = fileList.get(i);
                byte[] fileData = (byte[]) map.get("fileData");
                String filename = (String) map.get("filename");
                ByteArrayResource resource = new ByteArrayResource(fileData) {
                    @Override
                    public String getFilename() {
                        return filename;
                    }
                };
                body.add("image", resource);
            }
        }
        body.add("text", content);
        body.add("uid", uid);
        // 创建HttpEntity
        org.springframework.http.HttpEntity<MultiValueMap<String, Object>> requestEntity = new org.springframework.http.HttpEntity<>(body, headers);
        // 发送请求
        ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity,
                String.class);
        // 输出响应
        log.info("Response: " + response.getBody());
        return response.getBody();
    }

    public void deleteweibo(String uid, String weibo_id) {
        String urlPath = url + "/api/weibo/delete";
        log.info("用户：{}删除微博：{}", uid, weibo_id);
        Map<String, Object> data = new HashMap<>();
        data.put("uid", uid);
        data.put("weibo_id", weibo_id);
        String post = HttpUtil.post(urlPath, data);
        log.info("删除结果：{}", post);
    }
}
